// Copyright 2021 Espressif Systems
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//  ESPLocalStorageSchedules.swift
//  ESPRainMaker
//

import Foundation

// Protocol for managing local storage of schedule.
protocol ESPSchedulesStorageProtocol {
    func saveSchedules(schedules: [String: ESPSchedule])
    func fetchSchedules() -> [String: ESPSchedule]
    func cleanupSchedules()
}

class ESPLocalStorageSchedules: ESPLocalStorage, ESPSchedulesStorageProtocol {
    
    /// Method to save current schedule information locally.
    ///
    /// - Parameters:
    ///   - schedules: Dictionary with unique key and associated ESPSchedule object.
    func saveSchedules(schedules: [String: ESPSchedule]) {
        do {
            let encoded = try JSONEncoder().encode(schedules)
            saveDataInUserDefault(data: encoded, key: ESPLocalStorageKeys.scheduleDetails)
        } catch {
            print(error)
        }
    }
    
    /// Method to fetch locally stored schedule information for current user.
    ///
    /// - Returns: Dictionary of schedules with unique id as key.
    func fetchSchedules() -> [String: ESPSchedule] {
        var scheduleList: [String: ESPSchedule] = [:]
        do {
            if let scheduleData = getDataFromSharedUserDefault(key: ESPLocalStorageKeys.scheduleDetails) {
                scheduleList = try JSONDecoder().decode([String: ESPSchedule].self, from: scheduleData)
            }
            return scheduleList
        } catch {
            print(error)
            return scheduleList
        }
    }
    
    // Method to clean all Schedule information from local storage.
    func cleanupSchedules() {
        cleanupData(forKey: ESPLocalStorageKeys.scheduleDetails)
    }
    
}
